package com.bs.manager04.service.impl;

import com.bs.manager04.entity.User;
import com.bs.manager04.mapper.UserMapper;
import com.bs.manager04.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bs.manager04.utils.RedisUtils;
import com.bs.manager04.utils.TokenUtils;
import com.bs.manager04.utils.UUIDFactory;
import com.bs.manager04.utils.exception.NoAuthException;
import com.bs.manager04.utils.exception.NotUserException;
import com.bs.manager04.utils.jwt.JwtUtil;
import com.bs.manager04.utils.security.LoginUser;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Set;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author yao
 * @since 2022-12-17
 */
@Service("auth")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    AuthenticationManager manager;

    @Resource
    RedisUtils utils;

    @Resource
    HttpServletRequest request;
    @Override
    public String login(User user) {
        UsernamePasswordAuthenticationToken usernamePassword=new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());
        Authentication auth = manager.authenticate(usernamePassword);
        if(auth==null){
            throw new NotUserException("用户名或密码错误");
        }
        LoginUser loginUser =(LoginUser) auth.getPrincipal();
        //String token = UUIDFactory.UUID();
        String jwt = JwtUtil.createJWT(loginUser.getUsername());
        utils.set("user"+jwt,loginUser, TokenUtils.TOKEN_TIME);

        return jwt;
    }

    @Override
    public void loginout() {
        String token = request.getHeader(TokenUtils.TOKEN_NAME);
        utils.del("user"+token);
    }

    public boolean hasAuth(String auth){
        Authentication auths = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser =(LoginUser) auths.getPrincipal();
        Set<String> premission = loginUser.getUser().getPremission();
        boolean contains = premission.contains(auth);
        if(!contains){
            throw new NoAuthException("您没有访问权限，请联系管理员");
        }
        return contains;
    }
}
